import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthLoginDto } from './dto/auth-login.dto';
import { AdminUsersService } from '../admin-users/admin-users.service';
import { AdminUser } from 'src/admin-users/entities/admin-user.entity';
import { decrypt, md5password, passwordKeyStr } from '../utils/crypto-util';
import { RequltData } from '../common/result.interface';
import { ConfigService } from '@nestjs/config';
import { responseData } from '../common/response.handle';
import { RolePermissionService } from '../role-permission/role-permission.service';

@Injectable()
export class AuthService {
	constructor(
		private readonly adminUsersService: AdminUsersService,
		private readonly jwtService: JwtService,
		private readonly configService: ConfigService,
		private readonly rolePermissionService: RolePermissionService,
	) {}

	async login(loginDto: AuthLoginDto): Promise<RequltData<{ token: string; user: AdminUser }>> {
		const user = await this.adminUsersService.findOne({
			username: loginDto.username,
		});

		if (!user) {
			throw new HttpException(
				{
					code: HttpStatus.UNPROCESSABLE_ENTITY,
					data: null,
					msg: '用户名或密码错误',
				},
				HttpStatus.OK,
			);
		}

		// 密码对比
		const isValidPassword = user.password === md5password(decrypt(loginDto.password, passwordKeyStr));

		if (isValidPassword) {
			const token = this.jwtService.sign({
				userId: user.userId,
				roleId: user.roleId,
				username: user.username,
			});
			user.avatar = this.configService.get('host') + user.avatar;

			await this.adminUsersService.updateLoginTime(user.userId);

			return responseData({ token: 'Bearer ' + token, user: user }, '登录成功');
		} else {
			throw new HttpException(
				{
					code: HttpStatus.UNPROCESSABLE_ENTITY,
					data: null,
					msg: '用户名或密码错误',
				},
				HttpStatus.OK,
			);
		}
	}

	async getUserAllPermissionList(roleId: number) {
		return this.rolePermissionService.findRolePermissions(roleId);
	}

	async getUserAllMenuList(roleId: number) {
		return this.rolePermissionService.findRoleMenus(roleId);
	}

	getTokenData(token: string) {
		try {
			token = token.replace('Bearer ', '');
			const payload = this.jwtService.verify(token, {
				secret: this.configService.get('auth.secret'),
			});
			return payload;
		} catch (error) {
			throw new HttpException(
				{
					code: HttpStatus.UNAUTHORIZED,
					data: null,
					msg: '登录已过期',
				},
				HttpStatus.UNAUTHORIZED,
			);
		}
	}

	// findManyWithPagination(paginationOptions: IPaginationOptions) {
	//   return this.usersRepository.find({
	//     skip: (paginationOptions.page - 1) * paginationOptions.limit,
	//     take: paginationOptions.limit,
	//   });
	// }
	//
	// findOne(fields: EntityCondition<User>) {
	//   return this.usersRepository.findOne({
	//     where: fields,
	//   });
	// }
	//
	// update(id: number, updateProfileDto: UpdateUserDto) {
	//   return this.usersRepository.save(
	//     this.usersRepository.create({
	//       id,
	//       ...updateProfileDto,
	//     }),
	//   );
	// }
	//
	// async softDelete(id: number): Promise<void> {
	//   await this.usersRepository.softDelete(id);
	// }
}
